package cn.controller;

import cn.entity.Goods;
import cn.entity.Kind;
import cn.service.GoodsService;
import cn.service.KindService;
import cn.util.Const;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
//@Scope("prototype")
@RequestMapping("/goods")
public class GoodsController {//SSM
    @Autowired
    KindService kindService;
    @Autowired
    GoodsService goodsService;
    @RequestMapping("admin/list")
    public String list(Integer kid,String name, Integer pageNo, Model model){
        if(pageNo==null){
            pageNo=1;
        }
        //代码分页
        PageHelper.startPage(pageNo, Const.PAGESIZE);
        List<Goods> list=goodsService.find(kid,name);
        for(Goods v:list){
            if(v.getKid()!=null){
                Kind kind=kindService.selectByPrimaryKey(v.getKid());
                v.setKind(kind);
            }
        }
        //将结果封装到PageInfo
        PageInfo<Goods> pageInfo=new PageInfo<Goods>(list);
        model.addAttribute("name", name);
        model.addAttribute("pageInfo", pageInfo);
        return "admin/goods";
    }

    @RequestMapping("admin/delete/{id}")
    public String delete(@PathVariable Integer id){
       goodsService.deleteByPrimaryKey(id);
       return "redirect:/goods/admin/list";
    }
    @RequestMapping("admin/add")
    public String add(Goods goods){
        goods.setXiao(0);
        goods.setZan(0);
        goods.setIsdel(0);
        int n=goodsService.insert(goods);
        return "redirect:/goods/admin/list";
    }

    @RequestMapping("admin/update")
    public String update(Goods goods){
        int n=goodsService.updateByPrimaryKey(goods);
        return "redirect:/goods/admin/list";
    }
    @RequestMapping("jsonlist")
    @ResponseBody
    public List<Goods> jsonlist(){
        return goodsService.find(null, null);
    }

    @RequestMapping("json")
    @ResponseBody
    public Goods json(Integer id){
        return goodsService.selectByPrimaryKey(id);
    }

}
